#include "mushroom.h"
#include <QDebug>
#include <cstdlib>  // 用于生成随机数
#include <ctime>    // 用于时间种子

MushRoom::MushRoom() {
    MushRoom_Init();
    srand(time(0));  // 初始化随机数种子
}

void MushRoom::MushRoom_Init() {
    mushroom_kind = 0;
    mushroom_x = 0;
    mushroom_y = 0;
    mushroom_state = 0;
    mushroom_fall_down_distance = 19;
}

void MushRoom::MushRoom_Move(QVector<QVector<int>>::iterator it, Brick *r, Role *m) {
    brick = r;
    role = m;

    // 根据角色的颜色来决定蘑菇的种类
    if (role->colour == 1) {
        mushroom_kind = 1;
    } else {
        mushroom_kind = 2;
    }

    mushroom_x = *it->begin();
    mushroom_y = *(it->begin() + 1);
    mushroom_state = 1;
}

void MushRoom::Move_state() {
    // 随机概率控制蘑菇是否掉落
    int dropChance = rand() % 100;  // 生成0到99之间的随机数
    if (dropChance < 30) {  // 假设30%的概率蘑菇掉落
        if (mushroom_state != 0 && mushroom_state != -2) {
            if (mushroom_state <= 20) {
                mushroom_y -= 2;
                mushroom_state++;
            } else if (mushroom_state > 20) {
                mushroom_x += 2;
                mushroom_state++;
            }
            for (QVector < QVector < int >> ::iterator it = brick->m.begin()->begin(); it != brick->m.begin()->end(); it++) {
                if (*it->begin() - mushroom_x >= -50 && *it->begin() - mushroom_x <= 30 &&
                    *(it->begin() + 1) <= mushroom_y + 40 && *(it->begin() + 1) >= mushroom_y && *(it->begin() + 2) != 0) {
                    return;
                }
            }
            mushroom_state = -1;
            mushroom_y += 20 - mushroom_fall_down_distance;
            mushroom_fall_down_distance--;
        }
    }

    if (mushroom_y >= 460 && mushroom_state != 0) {
        if (mushroom_x - 330 <= role->x && mushroom_x - 270 >= role->x && mushroom_y - role->y == 5) {
            mushroom_state = 0;
            role->colour = mushroom_kind + 1;
            mushroom_fall_down_distance = 19;

            // 蘑菇掉落到角色身边时，增加角色的生命值
            int healthIncrease = rand() % 20 + 10;  // 随机增加10到30的生命值
            role->addHealth(healthIncrease);
            qDebug() << "Mushroom dropped! Health increased by " << healthIncrease;

            return;
        }
        mushroom_state = -2;
        mushroom_y = 460;
        mushroom_x -= 2;
    }
}
